package cn.fl.risk.controller;

import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.utils.*;
import cn.fl.capital.condition.CapOverdueHisQueryCondition;
import cn.fl.capital.constant.QueryConditionTabConstant;
import cn.fl.capital.service.ICapOverdueHisService;
import cn.fl.capital.vo.CapOverdueHisVO;
import cn.fl.capital.vo.CapTaskAccepterReportListVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import com.alibaba.dubbo.common.json.JSONObject;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Function: 催收报表
 * Created by Administrator on 2017/5/8.
 */
@Controller
@RequestMapping("/risk/collectReport")
public class RskCollectReportController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(RskCollectReportController.class);

    @Autowired
    private ICstBscInfoService cstBscInfoService;
    @Autowired
    private ICapOverdueHisService capOverdueHisService;

    /**
     * 到催收报表页面
     */
    @RequestMapping(value = "/toCollectPage.do", method = {RequestMethod.GET})
    public ModelAndView toCollectPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toCollectPage", "加载到催收报表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("risk/rskReport/rskCollectReport");
        return mav;
    }

    /**
     * 到催收报表页签页
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载到催收报表页签页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView();
        String queryType = request.getParameter("queryType");
        if ("1".equals(queryType)) {//绩效报表
            mav.setViewName("risk/rskReport/rskPerformanceList");
        } else if ("2".equals(queryType)) {//绩效明细报表
            mav.setViewName("risk/rskReport/rskPerformanceDtlList");
        } else if ("3".equals(queryType)) {//逾期报表
            mav.setViewName("risk/rskReport/rskOverDueReportList");
        } else if ("4".equals(queryType)) {//任务领取人报表
            mav.setViewName("risk/rskReport/rskTaskAccepterReportList");
        }
        // 事业部
        List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
        mav.addObject("buOrgCdList", JSON.toJSONString(orgList));

        return mav;
    }


    /**
     * 初始化绩效报表列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initPerformanceList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initPerformanceList(HttpServletRequest request, HttpServletResponse response) {
        //设置查询条件？
        CapOverdueHisQueryCondition condition = getCapOverdueHisQueryCondition(request);
        if(condition == null){
            return null;
        }
        CapOverdueHisVO vo = this.capOverdueHisService.searchPerformance(condition);
        if (null != vo) {
            List<CapOverdueHisVO> list = new ArrayList<>(1);
            list.add(vo);

            DecimalFormat df = new DecimalFormat("######0.00");//格式化保留两位小数
            //还款率 = 已还租金/逾期租金
            vo.setPaymentRate(df.format(DecimalUtils.div(vo.getPayAmount(), vo.getOverdueAmount(), 2)));
            ListPageVO<CapOverdueHisVO> listPage = new ListPageVO<CapOverdueHisVO>(list, 1);
            return listPage;
        }
        return new ListPageVO<CapOverdueHisVO>(new ArrayList<CapOverdueHisVO>(), 0);
    }

    /**
     * 初始化绩效明细报表列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initPerformanceDtlList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initPerformanceDtlList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        CapOverdueHisQueryCondition condition = getCapOverdueHisQueryCondition(request);
        if(condition == null){
            return null;
        }
        page.setCondition(condition);

        BaseLogUtils.info(logger, "initCapPayInfoList", "初始化绩效明细报表列表.", CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capOverdueHisService.searchDtlListPage(page);
        List<CapOverdueHisVO> list = (List<CapOverdueHisVO>) pager.getResultList();
        ListPageVO<CapOverdueHisVO> listPage = new ListPageVO<CapOverdueHisVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化任务人领取报表列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initTaskAccepterList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initTaskAccepterList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        CapOverdueHisQueryCondition condition = getCapOverdueHisQueryCondition(request);
        if(condition == null){
            return null;
        }
        page.setCondition(condition);

        BaseLogUtils.info(logger, "initCapPayInfoList", "初始化绩效明细报表列表.", CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capOverdueHisService.searchTaskAccepterListPage(page);
        List<CapTaskAccepterReportListVO> list = (List<CapTaskAccepterReportListVO>) pager.getResultList();
        ListPageVO<CapTaskAccepterReportListVO> listPage = new ListPageVO<CapTaskAccepterReportListVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 任务人迁出率报表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/taskAccepterOvdOutRate.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object taskAccepterOvdOutRate(HttpServletRequest request, HttpServletResponse response) {
        CapOverdueHisQueryCondition condition = getCapOverdueHisQueryCondition(request);
        if(condition == null){
            return null;
        }
        BaseLogUtils.info(logger, "taskAccepterOvdOutRate", "任务人迁出率报表.", CurrentThreadContext.getCurrentUserName());
        CapOverdueHisVO vo = this.capOverdueHisService.searchTaskAccepterOvdoutRate(condition);
        List<CapOverdueHisVO> voList = new ArrayList<>(1);
        if(vo != null){
            if (StringUtils.isNotEmpty(vo.getOverdueAmount()) && vo.getOverdueAmount().longValue() > 0L) {
                DecimalFormat df = new DecimalFormat("######0.00");//格式化保留两位小数
                //迁出率 = 迁出租金/所有逾期天数大于1天的逾期总租金
                vo.setPaymentRate(df.format(DecimalUtils.div(vo.getPenaltyAmount(), vo.getOverdueAmount(), 2)));
            }
            voList.add(vo);
        }
        ListPageVO<CapOverdueHisVO> listPage = new ListPageVO<>(voList, voList.size());
        return listPage;
    }

    /**
     * 任务人迁出明细报表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/taskAccepterOvdOutListReport.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object taskAccepterOvdOutListReport(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        CapOverdueHisQueryCondition condition = getCapOverdueHisQueryCondition(request);
        if(condition == null){
            return null;
        }
        condition.setOvdDays(2);
        condition.setQueryCondition(QueryConditionTabConstant.QUERY_TAB_GTE);
        page.setCondition(condition);
        BaseLogUtils.info(logger, "taskAccepterOvdOutListReport", "任务人迁出明细报表.", CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capOverdueHisService.searchTaskAccepterOvdReportPage(page);
        List<CapOverdueHisVO> list = (List<CapOverdueHisVO>) pager.getResultList();
        ListPageVO<CapOverdueHisVO> listPage = new ListPageVO<CapOverdueHisVO>(list, pager.getTotalCount());
        jsonObject.put("pageResult", listPage);
        return listPage;
    }

    /**
     * 任务人迁入率报表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/taskAccepterOvdDueInRate.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object taskAccepterOvdDueInRate(HttpServletRequest request, HttpServletResponse response) {
        CapOverdueHisQueryCondition condition = getCapOverdueHisQueryCondition(request);
        if(condition == null){
            return null;
        }

        BaseLogUtils.info(logger, "taskAccepterOvdDueInRate", "任务人迁入率报表.", CurrentThreadContext.getCurrentUserName());
        CapOverdueHisVO vo = this.capOverdueHisService.searchTaskAccepterOvdInRate(condition);
        List<CapOverdueHisVO> voList = new ArrayList<CapOverdueHisVO>(1);
        if(vo != null){
            if (StringUtils.isNotEmpty(vo.getOverdueAmount()) && vo.getOverdueAmount().longValue() > 0L) {
                DecimalFormat df = new DecimalFormat("######0.00");//格式化保留两位小数
                //迁入率 = 迁入租金/所有逾期天数大于30天的逾期总租金
                vo.setPaymentRate(df.format(DecimalUtils.div(vo.getPenaltyAmount(), vo.getOverdueAmount(), 2)));
            }
            voList.add(vo);
        }
        ListPageVO<CapOverdueHisVO> listPage = new ListPageVO<>(voList, voList.size());
        return listPage;
    }

    private CapOverdueHisQueryCondition getCapOverdueHisQueryCondition(HttpServletRequest request) {
        //设置查询条件？
        String buOrgCd = request.getParameter("buOrgCd");//事业部
        String ovdDaysMin = request.getParameter("ovdDaysMin");//逾期最小天数
        String ovdDaysMax = request.getParameter("ovdDaysMax");//逾期最大天数
        String ovdDtMin = request.getParameter("ovdDtMin");//逾期最小日期
        String ovdDtMax = request.getParameter("ovdDtMax");//逾期最大日期
        String collectUsrNm = request.getParameter("collectUsrNm");//责任人

        if(StringUtils.isBlank(ovdDtMin)||StringUtils.isBlank(ovdDtMax)){
            return null;
        }

        CapOverdueHisQueryCondition condition = new CapOverdueHisQueryCondition();
        if (StringUtils.isNotBlank(buOrgCd)) {
            condition.setBuOrgCd(buOrgCd);
        }
        if (StringUtils.isNotEmpty(ovdDaysMin)) {
            condition.setOvdDaysMin(Integer.parseInt(ovdDaysMin));
        }
        if (StringUtils.isNotEmpty(ovdDaysMax)) {
            condition.setOvdDaysMax(Integer.parseInt(ovdDaysMax));
        }
        if (StringUtils.isNotBlank(ovdDtMin)) {
            condition.setOvdDtMin(ovdDtMin);
        }
        if (StringUtils.isNotBlank(ovdDtMax)) {
            condition.setOvdDtMax(ovdDtMax);
        } else {
            condition.setOvdDtMax(DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(collectUsrNm)) {
            condition.setCollectUsrNm(collectUsrNm);
        }

        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());
        return condition;
    }


}
